<?php
       namespace App\Http\Controllers\home;
       use App\Http\Controllers\Controller;
	use Gregwar\Captcha\CaptchaBuilder;
	use Illuminate\Http\Request;
	use Session;
	use App\Model\User;
	use Illuminate\Support\Facades\Validator;
	use Illuminate\Support\Facades\Input;
	use Illuminate\Support\MessageBag;
	use Libs;
	use Illuminate\Support\Facades\DB;
       class LoginController extends Controller{
	     public $iphone_number="";
	     public $code_number="";
              public function login_list(Request $request){
		  if($request->session()->has('u_name')){
		   return redirect("/home/order_info/账号设置");
		  }else{
		   $arr=['u_phone'=>'中国','old_data'=>''];
                   return view('home.login.login')->with('abc',$arr);
                  }
               }
	      public function register_list(Request $request){
		 if($request->session()->has('u_name')){
		  return redirect("/home/order_info/账号设置");
		}else{
		  return view('home.login.register');
		}
       }
	
	public function captcha_list($tmp){
                  $builder = new CaptchaBuilder;
                  $builder->build($width = 100, $height = 40, $font = null);
                  $bb = $builder->inline();  //获取图形验证码的url
                  $phrase = $builder->getPhrase();//获取验证的内容 
                  Session::flash('milkcaptcha', $phrase);//将验证码内容存到session中
                ob_clean();
                //方法一:
                //header("Cache-Control: no-cache, must-revalidate");  
                //header('Content-Type: image/jpeg');  
                return $builder->output();

       }   
       public function do_sign(Request $request){
                $code = $request->input('code');
                if(Session::get('milkcaptcha')!=$code) {   
                        $title = array('content'=>'验证码错误','url'=>'/home/register');
                         return view('admin.alert',['data'=>$title]);
		
		 }
                //自动验证
		  $this->validate($request, [
                          'u_name'    =>'required|max:30|unique:mo_user',
                          'u_password'=>'required|min:4',
                         'u_email'=>'required|email|unique:mo_user',
                   ],
                      [
                           'u_name.required' => '用户名必须填写',
                           'u_name.unique'=>'用户名已存在',
                           'u_name.max'            => '用户名最多填写30个字符（一个中文占用两个字符）',
                           'u_password.required'     => '密码必须填写',
                          'u_password.min'=>'密码至少四位',
                          'u_email.email'=>'邮箱格式不对',
                          'u_email.required'=>'邮箱必须填写',
                          'u_email.unique'=>'邮箱已存在',
			
                 ]
          );
	 $u_salt=rand(1000,9999);
	 $data['u_name']= $request->input('u_name');
	 $data['u_email']=$request->input('u_email');
	$data['u_password']= md5( md5($request->input('u_password')).$u_salt);
	$data['u_salt']= $u_salt;
	$data['u_reg_time']=time();
	 //var_dump($data);die;
	 $user = new User();
	 $id=$user->get_verify($data);
	 if($id){
		 $title = array('content'=>'注册成功','url'=>'/home/login');
                 return view('admin.alert',['data'=>$title]);

	 }else{
		$title = array('content'=>'注册失败','url'=>'/home/register');
                 return view('admin.alert',['data'=>$title]);
	 }
	}
	public function do_login(Request $request){
		$data['u_name']=$request->input('u_name');
		$data['u_password']=$request->input('u_password');
		$data['u_sign']=$request->input('u_sign');
		$user = new User();
		if($request->input('u_sign') == 1){
        	$reData=$user->check_user($data);
		if(is_array($reData)){
		   if(md5(md5($request->input('u_password')).$reData['u_salt'])== $reData['u_password']){
			$request->session()->put('u_name',$reData['u_name']);
			$request->session()->put('u_id',$reData['u_id']);
		 	$title = array('content'=>'登录成功','url'=>'/');
	                 return view('admin.alert',['data'=>$title]);
		  }else{
			$title = array('content'=>'密码错误','url'=>'/home/login');
                         return view('admin.alert',['data'=>$title]);
		   }  
		}else if(is_string($reData)){
			$title = array('content'=>$reData,'url'=>'/home/login');
                         return view('admin.alert',['data'=>$title]);
		}
	    }elseif($request->input('u_sign') == 2){
		if($this->iphone_number == ""){
			$iphone_number['u_phone']=$request->input('u_phone');
			$rules = [
                         'u_phone'    =>'required|regex:/^1[34578]\d{9}$/',
                        ];
			 $message = [
                         'u_phone.required'  =>  '手机号必须填写',
                           'u_phone.regex'     =>  '手机格式不正确',
                       ];
		       $validator = Validator::make($iphone_number,$rules,$message );
		       if($validator->fails()){
			  $data=$validator->getMessageBag()->toArray();
			  $data['u_phone']=$data['u_phone'][0];
			  $data['old_data']=$request->input('u_phone');
			  return view('home.login.login')->with("abc",$data);
			}
	       }
	      //var_dump($this->code_number);
	       if(!$request->session()->has('code')){
		   $data['u_phone']="手机验证码不正确";
		   $data['old_data']=$request->input('u_phone');
		  return  view('home.login.login')->with("abc",$data);
		}
		if($this->iphone_number != $request->input('tele') || $request->session()->get('code') != $request->input('telcode')){
		   $data['u_phone']='手机验证错误';
		   $data['old_data']=$request->input('u_phone');
	           return  view('home.login.login')->with("abc",$data);
		}
		$data = DB::table('mo_user')->where('u_phone','=',$request->input('u_phone'))->first();
		if(count($data)){
			$request->session()->put('u_name',$data->u_name);
			$request->session()->put('u_id',$data->uid);
			  $title = array('content'=>'登录成功','url'=>'/');
                          return view('admin.alert',['data'=>$title]);
		}else{
			$res=$this->rand_str(6);
			$insertData['u_name'] = $res;
			$insertData['u_phone']= $request->input('u_phone');
			$id= DB::table('mo_user')->insertGetId($insertData);
			if($id){
				$request->session()->put('u_name',$res);
				$request->session()->put('u_id',$id);
				$title = array('content'=>'登录成功','url'=>'/');
                         	return view('admin.alert',['data'=>$title]);
			}
			
		}
	    }

	}
	public function rand_str($len = 4, $str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'){
    		return substr(str_shuffle($str), 0, $len);
        }
	public function check_code(Request $request){
		$iphone_number['u_phone']=$request->input('u_phone');
		$this->iphone_number=$request->input('u_phone');
		
		 $rules = [
			 'u_phone'    =>'required|regex:/^1[34578]\d{9}$/',
               		];

		  $message = [
			 'u_phone.required'  =>  '手机号必须填写',
                           'u_phone.regex'     =>  '手机格式不正确',
                       ];
	   $validator = Validator::make($iphone_number,$rules,$message );
	    if($validator->fails()){
		 return response()->json(array( 
			'success' => false,
			'errors' => $validator->getMessageBag()->toArray() ));
	  }else{
		$code_number=rand(100000,999999);
		$this->code_number=$code_number;
		$request->session()->put('code',$code_number);
		$reslut=$this->sendTemplateSMS($request->input('u_phone'),array($this->code_number,1),240793);
		return response()->json(array(
			'success' => true,
			'errors'  => array(),
			));
	  }
       
	}
      public function sendTemplateSMS($to,$datas,$tempId){
	    $accountSid= 'aaf98f8947f222a30147fb4668c60dfc';
	    $accountToken= 'a1b6e7ebc5dc4259a599c185b987bc79';
	    $appId='8a216da8623c38fd016241748fe202e7';
	    $serverIP='app.cloopen.com';
	    $serverPort='8883';
	    $softVersion='2013-12-26';

	    $rest = new Libs($serverIP,$serverPort,$softVersion);
	    $rest->setAccount($accountSid,$accountToken);
	    $rest->setAppId($appId);
	    $result = $rest->sendTemplateSMS($to,$datas,$tempId);
		return $result;

	}
	
   }
